﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class CharacterManager : MonoBehaviour
{
    public string Label="default";
    public Transform LoadingPanelTrans;
    LoadingPanel loadingPanel;
    bool m_AssetsReady = false;
    public Transform ButtonPanelTrans;
    public Dictionary<string, Button> btnDic;
    public Dictionary<string, GameObject> objDic;
    public Transform spawnParent;
    private void Awake()
    {
        btnDic = new Dictionary<string, Button>();
        objDic = new Dictionary<string, GameObject>();
        for (int i=0;i< ButtonPanelTrans.childCount; i++)
        {
            Transform child = ButtonPanelTrans.GetChild(i);
            if (!btnDic.ContainsKey(child.name))
            {
                Button btn = child.GetComponent<Button>();
                btnDic.Add(child.name, btn);
                btn.onClick.AddListener(() => { SpawnCharacter(btn.name); });
                btn.interactable = false;
            }
        }
    }
    // Start is called before the first frame update
    IEnumerator Start()
    {
        if(LoadingPanelTrans!=null)
            loadingPanel = new LoadingPanel(LoadingPanelTrans);
        var operateHandler = Addressables.LoadAssetsAsync<GameObject>(Label, OnLoadComplete);
        operateHandler.Completed += LoadAddressables_Completed;
        while (!operateHandler.IsDone)
        {
            //progressText.text = string.Format("{0:F1}%", operateHandler.PercentComplete * 100);
            loadingPanel.ShowProgress(operateHandler.PercentComplete);
            Debug.Log(operateHandler.PercentComplete);
            yield return null;
        }
        yield return null;
    }

    private void OnLoadComplete(GameObject obj)
    {
        if(!objDic.ContainsKey(obj.name))
        objDic.Add(obj.name, obj);
        if(btnDic.ContainsKey(obj.name))
            btnDic[obj.name].interactable = true;
    }

    private void LoadAddressables_Completed(AsyncOperationHandle<IList<GameObject>> obj)
    {
        loadingPanel.ShowProgress(obj.PercentComplete);
    }

    public void SpawnCharacter(string characterName) {
        Debug.Log(characterName);
        Vector3 position = Random.insideUnitSphere * 5;
        position.Set(position.x, 0, position.z);
        if (objDic.ContainsKey(characterName))
            Instantiate<GameObject>(objDic[characterName],position,Quaternion.identity,spawnParent);
    }
    private void OnDestroy()
    {

    }
}
